package v1

import (
	"blog/model"
	"blog/model/response"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加文章
func AddArticle(c *gin.Context) {
	var article model.Article
	_ = c.ShouldBindJSON(&article)
	code := model.CreateArticle(&article)
	c.JSON(
		http.StatusOK, gin.H{
			"status":  code,
			"message": response.GetMessage(code),
			"data":    article,
		},
	)

}

//查询分类文章
func GetCategoryArticles(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	articles, code, total := model.GetCategoryArticles(id, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    articles,
		"total":   total,
		"message": response.GetMessage(code),
	})
}

//查询单个文章
func GetArticleInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	article, code := model.GetArticleInfo(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    article,
		"message": response.GetMessage(code),
	})
}

//查询文章列表
func GetArticles(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	articles, code, total := model.GetArticles(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    articles,
		"total":   total,
		"message": response.GetMessage(code),
	})
}

//编辑文章
func EditArticle(c *gin.Context) {
	var article model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&article)
	code := model.EditArticle(id, &article)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}

// 删除文章
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArticle(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}
